package com.moss.cloud.log.message;

import com.alibaba.fastjson2.JSON;
import com.moss.cloud.common.core.constant.MsgGroup;
import com.moss.cloud.common.core.constant.MsgTopic;
import com.moss.cloud.common.core.model.dto.MessageDTO;
import com.moss.cloud.common.core.model.dto.OperationLogDTO;
import com.moss.cloud.log.model.po.OperationLog;
import com.moss.cloud.log.service.IOperationLogService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;

import java.util.LinkedHashMap;

/**
 * @author 瑾年 集群模式，日志服务消费后不会再被其他服务消费
 * @data 2023年3月16日
 */
@Slf4j
@Component
@RocketMQMessageListener(consumerGroup = MsgGroup.MOSS_CLOUD_LOG,topic = MsgTopic.SYSTEM_LOG_MESSAGE,messageModel = MessageModel.CLUSTERING)
public class ListenerOperationMessage implements RocketMQListener<MessageDTO> {
    private final IOperationLogService operationLogService;

    public ListenerOperationMessage(IOperationLogService operationLogService) {
        this.operationLogService = operationLogService;
    }

    /**
     * 监听日志消息队列
     *
     * @param messageDTO 消息
     */
    @Override
    public void onMessage(MessageDTO messageDTO) {
        log.info("监听到日志消息:{}", messageDTO.toString());
        LinkedHashMap data = (LinkedHashMap) messageDTO.getData();
        log.info("日志消息对象:{}", data.toString());
        OperationLogDTO dto = JSON.parseObject(JSON.toJSONString(data), OperationLogDTO.class);
        OperationLog operationLog = new OperationLog();
        BeanUtils.copyProperties(dto, operationLog);
        operationLogService.saveOperationLog(operationLog);
    }
}
